<template>
  <el-dialog title="二维码" v-model="openRegQr" width="600px" append-to-body>
    <!-- <el-image :src="tinyCodeSrc"></el-image> -->
    <div v-if="openRegQr">
      <canvas id="canvasReg" :width="560" :height="560"></canvas>
    </div>
  </el-dialog>
</template>

<script setup>
import QRCode from "qrcode";
const { proxy } = getCurrentInstance();
const openRegQr = ref(false);
const tinyCodeSrc = ref(null);
const tiny_str = ref(null);
const data = ref(null);
// 打开弹窗
function open(row) {
  openRegQr.value = true;
  tinyCodeSrc.value = null;
  data.value = row
  getQrcode();
}

// 暴露出去
defineExpose({
  open,
})

// 获取二维码
function getQrcode() {
  tiny_str.value =
    "https://opr.gtcharger.com?reg=" + data.value;
  createRegQrcode();
}

// 生成二维码
function createRegQrcode() {
  QRCode.toDataURL(tiny_str.value, { errorCorrectionLevel: "H" })
    .then((url) => {
      tinyCodeSrc.value = url.replace(/[\r\n]/g, "");
    })
    .catch((err) => {
      ElNotification({
        message: "二维码生成错误" + err,
        type: "error",
      });
      return;
    });
  setTimeout(() => {
    drawRegQrcode();
  }, 100);
}

// 绘制二维码
function drawRegQrcode() {
  let canvas = document.getElementById("canvasReg");
  let ctx = canvas.getContext("2d"); // 创建画布
  let img = new Image(); // 因为拿不到图片静态资源，所以创建图片标签
  img.setAttribute("crossOrigin", "anonymous"); // 解决图片跨域问题,也要放到赋值前，否贼大部分浏览器会报错
  img.src = tinyCodeSrc.value;
  // 加载图片
  img.onload = () => {
    // 绘制图片
    ctx.drawImage(img, 0, 0, 560, 560);
    // 合成图片
    let imgUrl = canvas.toDataURL("image/jpg");
    tinyCodeSrc.value = imgUrl;
  };
}
</script>
  
<style scoped>
.tiny_qr {
  width: 4.8cm;
}
</style>